// 测试脚本：用户取消收藏视频功能
const axios = require('axios');

// 测试数据
const TEST_DATA = {
  user: 'user',
  password: '123456',
  videoId: 6
};

// API 基础URL
const API_BASE_URL = 'http://localhost:3000';

// 测试函数
async function runUnfavoriteTest() {
  console.log('开始测试用户取消收藏视频功能...');
  console.log(`测试用户: ${TEST_DATA.user}`);
  console.log(`视频ID: ${TEST_DATA.videoId}`);
  console.log('================================');
  
  let token = null;
  
  try {
    // 1. 用户登录
    console.log('1. 执行用户登录...');
    const loginResponse = await axios.post(`${API_BASE_URL}/api/auth/login`, {
      username: TEST_DATA.user,
      password: TEST_DATA.password
    });
    
    console.log('登录响应:', loginResponse.data);
    
    // 解析嵌套的数据格式
    if (loginResponse.data.code === 200 && loginResponse.data.data?.token) {
      token = loginResponse.data.data.token;
      console.log('✅ 登录成功！');
      console.log(`用户ID: ${loginResponse.data.data.user?.id || '未知'}`);
      console.log(`用户昵称: ${loginResponse.data.data.user?.nickname || '未知'}`);
    } else {
      throw new Error(`登录失败: ${loginResponse.data.message || JSON.stringify(loginResponse.data)}`);
    }
    
    // 2. 取消收藏视频
    console.log('\n2. 执行取消收藏视频...');
    const unfavoriteResponse = await axios.post(
      `${API_BASE_URL}/api/interactions/unfavorite`,
      { videoId: TEST_DATA.videoId },
      { headers: { Authorization: `Bearer ${token}` } }
    );
    
    console.log('取消收藏响应:', unfavoriteResponse.data);
    
    // 解析嵌套的响应格式
    if (unfavoriteResponse.data.code === 200 || unfavoriteResponse.data.success === true) {
      console.log('✅ 取消收藏成功！');
      console.log(`响应信息: ${unfavoriteResponse.data.message || '取消收藏成功'}`);
    } else {
      throw new Error(`取消收藏失败: ${unfavoriteResponse.data.message || JSON.stringify(unfavoriteResponse.data)}`);
    }
    
    // 3. 验证收藏状态（应该为未收藏）
    console.log('\n3. 验证收藏状态...');
    const statusResponse = await axios.get(
      `${API_BASE_URL}/api/interactions/favorite/status?videoId=${TEST_DATA.videoId}`,
      { headers: { Authorization: `Bearer ${token}` } }
    );
    
    console.log('收藏状态响应:', statusResponse.data);
    
    // 解析嵌套的响应格式
    let isFavorited = false;
    if (statusResponse.data.code === 200 && statusResponse.data.data) {
      isFavorited = statusResponse.data.data.favorited || false;
    } else if (statusResponse.data.success === true) {
      isFavorited = statusResponse.data.favorited || statusResponse.data.isFavorited || false;
    }
    
    console.log(`✅ 收藏状态: ${isFavorited ? '已收藏' : '未收藏'}`);
    
    // 4. 获取视频信息，验证collect_count是否更新
    console.log('\n4. 获取视频信息，验证收藏数...');
    const videoResponse = await axios.get(`${API_BASE_URL}/api/videos/${TEST_DATA.videoId}`);
    
    console.log('视频信息响应:', videoResponse.data);
    
    // 解析嵌套的响应格式
    let collectCount = 0;
    let videoTitle = '';
    
    if (videoResponse.data.code === 200 && videoResponse.data.data) {
      collectCount = videoResponse.data.data.collect_count || 0;
      videoTitle = videoResponse.data.data.title || '';
    } else if (videoResponse.data.success === true && videoResponse.data.data) {
      collectCount = videoResponse.data.data.collect_count || 0;
      videoTitle = videoResponse.data.data.title || '';
    }
    
    console.log(`✅ 视频收藏数: ${collectCount}`);
    console.log(`✅ 视频标题: ${videoTitle}`);
    
    // 5. 验证测试结果
    if (!isFavorited) {
      console.log('\n✅ 测试验证: 用户已成功取消收藏视频ID 6');
      console.log(`✅ 视频当前收藏数: ${collectCount}`);
    } else {
      console.log('\n❌ 测试验证: 用户仍收藏视频ID 6');
    }
    
    console.log('\n================================');
    console.log('🎉 测试完成！所有测试步骤均已成功执行。');
    
  } catch (error) {
    console.error('\n❌ 测试失败！');
    if (error.response) {
      console.error(`错误信息: ${error.response.data.message || JSON.stringify(error.response.data)}`);
      console.error(`状态码: ${error.response.status}`);
    } else if (error.request) {
      console.error('网络错误，请检查服务器是否运行正常');
    } else {
      console.error(`错误: ${error.message}`);
    }
  }
}

// 运行测试
runUnfavoriteTest();